import React, { Component } from "react";
import {
  Divider,
  Table,
  Select,
  Button,
  Row,
  Col,
  Modal,
  Form,
  Input,
  Popconfirm,
  message,
} from "antd";
import {
  fetchAllForm,
  loadfetchAllForm,
  deleteForm,
  updateStateForm,
  loadType,
  getLicense,
  getCode,
} from "@service/form";
import { CopyToClipboard } from "react-copy-to-clipboard";
import "./index.scss";
import "./classifyButton.scss";
import ClassifyButton from "./classifyButton";
import UploadForm from "./upload";

const CreateForm = Form.create({ name: "form_in_modal" })(
  class extends React.Component {
    constructor() {
      super();
      this.state = {
        formLayout: "horizontal",
        inputVisible: false,
        inputValue: "",
      };
    }

    render() {
      const { visible, onCreate, onCancel, form } = this.props;
      const { getFieldDecorator } = form;
      const { formLayout } = this.state;
      const { TextArea } = Input;
      const formItemLayout =
        formLayout === "horizontal"
          ? {
            labelCol: { span: 5 },
            wrapperCol: { span: 13 },
          }
          : null;
      return (
        <Modal
          visible={visible}
          title="新建表单"
          okText="确认"
          cancelText="取消"
          onCancel={onCancel}
          onOk={onCreate}
          destroyOnClose
        >
          <Form layout={formLayout}>
            <Form.Item label="Form ID" {...formItemLayout}>
              {getFieldDecorator("id", {
                rules: [
                  { required: true, message: "请输入Form ID" },
                  { max: 30, message: "最大30个字符" },
                ],
              })(<Input />)}
            </Form.Item>
            <Form.Item label="表单名称" {...formItemLayout}>
              {getFieldDecorator("name", {
                rules: [
                  { required: true, message: "请输入表单名称" },
                  { max: 30, message: "最大30个字符" },
                ],
              })(<Input />)}
            </Form.Item>
            <Form.Item label="描述" {...formItemLayout}>
              {getFieldDecorator("description", {
                rules: [{ max: 255, message: "最大255个字符" }],
              })(<TextArea rows={4} />)}
            </Form.Item>
            <Form.Item label="版本号" {...formItemLayout}>
              {getFieldDecorator("version", {
                rules: [{ max: 30, message: "最大30个字符" }],
              })(<Input />)}
            </Form.Item>
            <Form.Item label="应用类型" {...formItemLayout}>
              {getFieldDecorator("classify")(<ClassifyButton />)}
            </Form.Item>
          </Form>
        </Modal>
      );
    }
  }
);

export default class index extends Component {
  state = {
    dataSource: [],
    state: "",
    visibleA: false,
    visibleB: false,
    selections: [],
    beforeInfo: "",
    endInfo: "",
    userName: "测试用户",
    isShow: false,
    machineCode: "",
  };

  columns = [
    {
      title: "Form ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "表单名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "描述",
      dataIndex: "description",
      key: "description",
    },
    {
      title: "版本号",
      dataIndex: "version",
      key: "version",
    },
    {
      title: "应用类型",
      dataIndex: "classify",
      key: "classify",
    },
    {
      title: "状态",
      dataIndex: "state",
      key: "state",
      render: (_, record) => (
        <div>
          {record.state === "0" ? (
            <a href="#" className="Unopened">
              ● 未启用
            </a>
          ) : (
            <a href="#" className="opened">
              ● 已启用
            </a>
          )}
        </div>
      ),
    },
    {
      title: "操作",
      key: "operate",
      render: (_, record) => (
        <div className="manage_control">
          <a
            href="#"
            onClick={() =>
              this.handleUpdateState(
                record._id,
                record.state === "1" ? "0" : "1"
              )
            }
          >
            {record.state === "0" ? "启用" : "停用"}
          </a>
          <a href="#" onClick={() => this.handleEdit(record._id)}>
            编辑
          </a>
          <Popconfirm
            title="是否删除？"
            okText="确定"
            cancelText="取消"
            onConfirm={() => this.handleDelete(record._id)}
          >
            {record.state === "0" ? (
              <a href="#">删除</a>
            ) : (
              <a href="#" disabled>
                删除
              </a>
            )}
          </Popconfirm>
        </div>
      ),
    },
  ];

  componentDidMount = () => {
    // const list = await getLicense();
    // if (list) {
    //   this.setState({
    //     beforeInfo: new Date(list.data.start).toLocaleDateString(),
    //     endInfo: new Date(list.data.expire).toLocaleDateString(),
    //     isShow: true,
    //   });
    //   localStorage.setItem("TIME", new Date(list.data.expire).getTime());
    // }
    this.getLicenses();
    this.getList();
    this.getSelections();
  };

  getList = async () => {
    const { classify } = this.state;
    let result;
    if (classify) {
      result = await fetchAllForm({
        params: {
          classify,
        },
      });
    } else {
      result = await fetchAllForm();
    }
    this.setState({
      dataSource: result.data,
    });
  };

  getLicenses = async () => {
    const list = await getLicense();
    if (list) {
      // const licDate = Date.parse(
      //   new Date(list.data.expire).toLocaleDateString()
      // );
      // const newDate = new Date(
      //   licDate - 30 * 24 * 60 * 60 * 1000
      // ).toLocaleDateString();
      this.setState({
        beforeInfo: new Date(list.data.start).toLocaleDateString(),
        endInfo: new Date(list.data.expire).toLocaleDateString(),
        isShow: true,
      });
    }
  };

  getSelections = async () => {
    const result = await loadType();
    this.setState({
      selections: result.data,
    });
  };

  getMachineCode = async () => {
    const result = await getCode();
    if (result) {
      this.setState({
        machineCode: result.data,
      });
    }
  };

  showModal = () => {
    this.setState({ visibleA: true });
  };

  showMode = () => {
    this.getMachineCode();
    this.setState({
      visibleB: true,
    });
  };

  handleUpdateState = async (id, state) => {
    const list = await updateStateForm(id, state);
    if (list) {
      this.getList();
    }
  };

  handleDelete = async id => {
    const list = await deleteForm(id);
    if (list) {
      this.getList();
    }
  };

  handleEdit = id => {
    // this.props.history.push(`/design/${id}`);
    window.open(`/design/${id}`, "_blank");
  };

  handleCancel = () => {
    this.setState({ visibleA: false });
  };

  handleOK = () => {
    this.setState({ visibleB: false });
  };

  handleOff = () => {
    this.setState({ visibleB: false });
  };

  handleCreate = async () => {
    const { form } = this.formRef.props;
    let value;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      value = values;
      form.resetFields();
      this.setState({ visibleA: false });
    });
    const list = await loadfetchAllForm(value);
    if (list) {
      this.getList();
      this.getSelections();
    }
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };

  handleChange = classify => {
    this.setState(
      {
        state: classify,
        classify,
      },
      () => this.getList()
    );
  };

  render() {
    const {
      dataSource,
      state,
      selections,
      beforeInfo,
      endInfo,
      userName,
      isShow,
      machineCode,
    } = this.state;
    return (
      <div className="holder">
        <span className="formlist">表单列表</span>
        <a onClick={this.showMode}>授权管理</a>
        <Modal
          title="授权管理"
          okText="确认"
          cancelText="取消"
          visible={this.state.visibleB}
          onOk={this.handleOK}
          onCancel={this.handleOff}
        >
          <CopyToClipboard
            onCopy={() => message.success("复制成功！")}
            text={machineCode}
          >
            <div>
              {machineCode ? <Input value={machineCode} disabled /> : null}
            </div>
          </CopyToClipboard>
          <div style={{ marginTop: 25 }}>
            <label>用户名称：</label>
            {userName}
          </div>
          <div style={{ marginTop: 25, marginBottom: 25 }}>
            <label>使用期限：</label>
            {beforeInfo}
            <span style={isShow ? { display: "inline" } : { display: "none" }}>
              -
            </span>
            {endInfo}
          </div>
          <UploadForm />
        </Modal>
        <Divider />
        <Row>
          <Col span={18} />
          <Col span={2}>
            <Select
              value={state}
              style={{ width: 110 }}
              onChange={this.handleChange}
            >
              <Select.Option value="">全部类型</Select.Option>
              {selections.map((item, index) => {
                return (
                  <Select.Option value={item.name} key={index}>
                    {item.name}
                  </Select.Option>
                );
              })}
            </Select>
          </Col>
          <Col span={1} />
          <Col span={3}>
            <Button
              type="primary" icon="plus"
              onClick={this.showModal}
            >
              新建表单
            </Button>
            <CreateForm
              wrappedComponentRef={this.saveFormRef}
              visible={this.state.visibleA}
              onCancel={this.handleCancel}
              onCreate={this.handleCreate}
              style={{ marginTop: 5 }}
            />
          </Col>
        </Row>
        <Row style={{ height: 25 }} />
        <Table
          dataSource={dataSource}
          columns={this.columns}
          locale={{
            emptyText: "未发现任何数据",
          }}
        />
      </div>
    );
  }
}
